package cn.wit.summit.chwan.ui.fragment;

import android.os.Bundle;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.content.ContextCompat;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.TextView;

import com.google.gson.Gson;

import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;
import cn.wit.summit.chwan.R;
import cn.wit.summit.chwan.adapters.HomeIndexAdapter;
import cn.wit.summit.chwan.models.db.NetResultCacheTable;
import cn.wit.summit.chwan.models.dbmanager.NetResultCacheManager;
import cn.wit.summit.chwan.models.dto.GameListBaseBean;
import cn.wit.summit.chwan.models.dto.PersonHomeDataUrl;
import cn.wit.summit.chwan.models.response.IndexBeanV3Response;
import cn.wit.summit.chwan.models.response.MakeMoneyIndexResponseV3;
import cn.wit.summit.chwan.models.response.ResponseBase;
import cn.wit.summit.chwan.net.NetCallBack;
import cn.wit.summit.chwan.net.RpcConstant;
import cn.wit.summit.chwan.retrofit.ApiUtil;
import cn.wit.summit.chwan.retrofit.MyCallback;
import cn.wit.summit.chwan.retrofit.RetrofitManager;
import cn.wit.summit.chwan.ui.activity.MainActivity;
import cn.wit.summit.chwan.ui.base.BaseFragment;
import cn.wit.summit.chwan.ui.base.MyApplication;
import cn.wit.summit.chwan.utils.AccountBean;
import cn.wit.summit.chwan.utils.AccountUtil;
import cn.wit.summit.chwan.utils.IntentUtil;
import cn.wit.summit.chwan.utils.LogUtils;
import cn.wit.summit.chwan.utils.NetWorkUtils;
import cn.wit.summit.chwan.utils.StringUtils;
import cn.wit.summit.chwan.utils.ToastUtils;
import cn.wit.summit.chwan.widgets.MessageDialog;
import io.supercharge.shimmerlayout.ShimmerLayout;
import retrofit2.Retrofit;

/**
 * Created by Alan on 2018/9/5.
 */

public class TodayRewardFragment extends BaseFragment {

    @Bind(R.id.todayRewardTopScoreTv)
    TextView todayRewardTopScoreTv;
    @Bind(R.id.todayRewardTopMoneyTv)
    TextView todayRewardTopMoneyTv;
    @Bind(R.id.todayRewardTopLeftTv)
    TextView todayRewardTopLeftTv;
    @Bind(R.id.todayRewardTopRightTv)
    TextView todayRewardTopRightTv;
    @Bind(R.id.todayRewardRv)
    RecyclerView todayRewardRv;
    @Bind(R.id.shimmerLayout)
    ShimmerLayout shimmerLayout;
    @Bind(R.id.todayRewardTopBt)
    Button todayRewardTopBt;

    private RetrofitManager retrofitManager;
    private Retrofit retrofit;
    private ApiUtil api;
    private Retrofit retrofitLogin;
    private ApiUtil apiLogin;

    private int pn = 1;
    private NetResultCacheTable table = null;

    private HomeIndexAdapter adapter;
    private List<HomeIndexAdapter.ViewBean> datas = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_today_reward, container, false);
        ButterKnife.bind(this, view);

        retrofitManager = RetrofitManager.getInstance(getActivity());
        retrofit = retrofitManager.getRetrofit();
        api = retrofit.create(ApiUtil.class);
        retrofitLogin = retrofitManager.getLoginRetrofit();
        apiLogin = retrofitLogin.create(ApiUtil.class);

        initListView();
        initData();
        return view;
    }

    private void initListView() {
        adapter = new HomeIndexAdapter(getActivity(), datas);
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getActivity());
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        todayRewardRv.setLayoutManager(linearLayoutManager);
        todayRewardRv.setAdapter(adapter);
        todayRewardRv.setFocusable(false);
    }

    private void initData() {
        try {
            Map<String, String> tempMap = new HashMap<>();
            tempMap.put("pn", pn + "");
            String requestStr = new Gson().toJson(tempMap);
            table = NetResultCacheManager.getInstance().getDataByUrl(RpcConstant.forumRootUrl + RpcConstant.homePageV3, requestStr);
            if (table != null && !StringUtils.isEmpty(table.getResponseStr())) {
                hideSkeleton();
                String data = table.getResponseStr();
                ResponseBase<IndexBeanV3Response> temp = fromJsonObject(data, IndexBeanV3Response.class);
                updataUi(temp.getData_info());
            } else {
                initSkeleton();
                showSkeleton();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

        getIndexData();
    }

    private int mShimmerColor;
    private boolean mShimmer = true;
    private int mShimmerDuration = 1200;
    private int mShimmerAngle = 20;
    View innerView;

    private void initSkeleton() {
        mShimmerColor = ContextCompat.getColor(getActivity(), R.color.shimmer_color);

        shimmerLayout.setShimmerColor(mShimmerColor);
        shimmerLayout.setShimmerAngle(mShimmerAngle);
        shimmerLayout.setShimmerAnimationDuration(mShimmerDuration);

        innerView = LayoutInflater.from(getActivity()).inflate(R.layout.fragment_today_reward_skeleton, shimmerLayout, false);
        shimmerLayout.addView(innerView);
        shimmerLayout.addOnAttachStateChangeListener(new View.OnAttachStateChangeListener() {
            @Override
            public void onViewAttachedToWindow(View v) {
                shimmerLayout.startShimmerAnimation();
            }

            @Override
            public void onViewDetachedFromWindow(View v) {
                if (shimmerLayout!=null)
                    shimmerLayout.stopShimmerAnimation();
            }
        });
    }

    public <T> ResponseBase<T> fromJsonObject(String reader, Class<T> clazz) {
        Type type = new NetCallBack.ParameterizedTypeImpl(ResponseBase.class, new Class[]{clazz});
        return new Gson().fromJson(reader, type);
    }

    private void showSkeleton() {
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        shimmerLayout.setVisibility(View.VISIBLE);
        todayRewardRv.setVisibility(View.GONE);
        shimmerLayout.startShimmerAnimation();
    }

    private void hideSkeleton() {
        if (innerView == null) initSkeleton();
        if (innerView == null) return;
        shimmerLayout.setVisibility(View.GONE);
        todayRewardRv.setVisibility(View.VISIBLE);
        shimmerLayout.stopShimmerAnimation();
    }

    private void getIndexData() {
        int uId = 0;
        AccountBean accountBean = AccountUtil.getInstance().getAccountData();
        if (accountBean != null) {
            uId = AccountUtil.getInstance().getUid();
        }
        api.getIndexDataV3(uId, uId, pn).enqueue(new MyCallback<ResponseBase<IndexBeanV3Response>>() {
            @Override
            public void onSuccess(ResponseBase<IndexBeanV3Response> model) {
                if (pn == 1) {
                    Gson gson = new Gson();
                    Map<String, String> tempMap = new HashMap<>();
                    tempMap.put("pn", pn + "");
                    String requestStr = gson.toJson(tempMap);
                    String retStr = gson.toJson(model);
                    String retUrl = RpcConstant.forumRootUrl + RpcConstant.homePageV3;
                    LogUtils.e("retUrl:" + retUrl + "\nrequestStr:" + requestStr + "\nretStr:" + retStr);
                    NetResultCacheManager.getInstance().insertData(retUrl, requestStr, retStr);
                }

                IndexBeanV3Response data = model.getData_info();
                hideSkeleton();
                updataUi(data);
            }

            @Override
            public void onFailure(int code, String msg) {
                showToast(msg);
            }
        });
    }

    private void updataUi(IndexBeanV3Response data) {
        IndexBeanV3Response.CreditInfoBean mCreditInfoBean = data.getCredit_info();
        if (mCreditInfoBean != null) {
            todayRewardTopScoreTv.setText(mCreditInfoBean.getScore() + "");
            MyApplication.downLoadRard = mCreditInfoBean.getDown_reward();
            MyApplication.downLoadWeekNum = mCreditInfoBean.getWeek_surplus();
            MyApplication.downLoadDayNum = mCreditInfoBean.getDay_surplus();
            todayRewardTopMoneyTv.setText(mCreditInfoBean.getDown_reward() + "");
            todayRewardTopLeftTv.setText(mCreditInfoBean.getDay_surplus() + "");
            todayRewardTopRightTv.setText(mCreditInfoBean.getWeek_surplus() + "");

            if (mCreditInfoBean.getCredit_task_status()==0) {
                todayRewardTopBt.setText(getActivity().getResources().getString(R.string.makemoney_t18_str));
                todayRewardTopBt.setEnabled(false);
            } else if (mCreditInfoBean.getCredit_task_status()==1) {
                todayRewardTopBt.setText(getActivity().getResources().getString(R.string.makemoney_t7_str));
                todayRewardTopBt.setEnabled(true);
            } else if (mCreditInfoBean.getCredit_task_status()==2) {
                todayRewardTopBt.setText(getActivity().getResources().getString(R.string.makemoney_t19_str));
                todayRewardTopBt.setEnabled(false);
            }
        } else {
            todayRewardTopScoreTv.setText("--");
            todayRewardTopMoneyTv.setText("-");
            todayRewardTopLeftTv.setText("-");
            todayRewardTopRightTv.setText("-");
        }

        List<GameListBaseBean> list = data.getGame_list();
        datas.clear();
        MyApplication.todayWard.clear();
        datas.add(new HomeIndexAdapter.ViewBean(HomeIndexAdapter.ViewType.TYPE_LINE));
        for (int i = 0; list != null && i < list.size(); i++) {
            MyApplication.todayWard.put(list.get(i).getGame_id(), list.get(i).getGame_id());
            datas.add(new HomeIndexAdapter.ViewBean(HomeIndexAdapter.ViewType.TYPE_ITEM, list.get(i), MyApplication.downLoadRard));
        }
        adapter.notifyDataSetChanged();
    }

    @Override
    public void onResume() {
        super.onResume();
        getUserinfo();
        getIndexData();
    }

    @Override
    public void onHiddenChanged(boolean hidden) {
        super.onHiddenChanged(hidden);
        if (!hidden) {
            getUserinfo();
            getIndexData();
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }

    @OnClick({R.id.todayRewardTopLeftOneRl, R.id.todayRewardTopBt, R.id.todayRewardTopRightOneRl
            , R.id.todayRewardTopLeftTwoRl, R.id.todayRewardTopRightTwoRl})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.todayRewardTopLeftOneRl:
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                String url2 = RpcConstant.forumLoginRootUrl + "static_v3/credit.html";
                IntentUtil.getInstance().goShareWebActivity(getActivity(), url2);
                break;
            case R.id.todayRewardTopBt:
                getRewardV3();
                break;
            case R.id.todayRewardTopRightOneRl:
                ((MainActivity)(getActivity())).changTab(2);
                break;
            case R.id.todayRewardTopLeftTwoRl:
                break;
            case R.id.todayRewardTopRightTwoRl:
//                startActivity(new Intent(getActivity(), DailyNewActivity.class));
                break;
        }
    }

    private void getRewardV3() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.getRewardV3(uid, token).enqueue(new MyCallback<ResponseBase<MakeMoneyIndexResponseV3>>() {
                        @Override
                        public void onSuccess(ResponseBase<MakeMoneyIndexResponseV3> model) {

                            if (model.getCode() == 600 && model.getSucc() == 1) {
                                todayRewardTopBt.setText(getActivity().getResources().getString(R.string.makemoney_t19_str));
                                todayRewardTopBt.setEnabled(false);
                                getIndexData();
                                showMsgDialog();
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                            }
                            ToastUtils.getInstance(getActivity()).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void getUserinfo() {
        if (NetWorkUtils.isNetworkConnected(getActivity())) {
            try {
                if (AccountUtil.getInstance().getUid() != 0) {
                    int uid = AccountUtil.getInstance().getUid();
                    String token = AccountUtil.getInstance().getToken();
                    apiLogin.checkToken(uid, token).enqueue(new MyCallback<ResponseBase<PersonHomeDataUrl>>() {
                        @Override
                        public void onSuccess(ResponseBase<PersonHomeDataUrl> model) {
                            PersonHomeDataUrl data = model.getData_info();
                            if (data != null) {
                                data.setToken(AccountUtil.getInstance().getToken());
                                AccountUtil.getInstance().saveAccountData(data);
                            }
                        }

                        @Override
                        public void onFailure(int code, String msg) {
                            if (code == 60001) {
                                AccountUtil.getInstance().accountLoginOut(getActivity());
                            }
                            ToastUtils.getInstance(getActivity()).showToastSystem(msg);
                        }
                    });
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private void showMsgDialog() {
        final MessageDialog messageDialog = new MessageDialog(getActivity());
        messageDialog.show();
        messageDialog.setTitle(getResources().getString(R.string.comment_dialog_title_str));
        messageDialog.setMsg("已领取成功，请到钱包中查看!");
        messageDialog.setCancelBtn(getResources().getString(R.string.trevi_dialog_bt_str), new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
            }
        });
        messageDialog.setOkBtn("查看钱包", new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                messageDialog.dismiss();
                if (AccountUtil.getInstance().getUidNotToLogin(getActivity()) == 0) return;
                IntentUtil.getInstance().goShareWebActivity(getActivity(), MyApplication.cfgPlug.getValue_wallet_url_v2());
            }
        });
    }
}
